package com.gaoyi.crm.repository;

import android.text.TextUtils;

import com.gaoyi.crm.R;
import com.gaoyi.crm.apiresult.ApiResultData;
import com.gaoyi.crm.apiresult.PagedList;
import com.gaoyi.crm.callback.OnResultListener;
import com.gaoyi.crm.constant.ApiStatus;
import com.gaoyi.crm.constant.DbMsg;
import com.gaoyi.crm.db.dao.PmnDao;
import com.gaoyi.crm.db.dto.PmnDto;
import com.gaoyi.crm.db.entity.Pmn;
import com.gaoyi.crm.db.entity.PmnWithAttach;
import com.gaoyi.crm.db.entity.PmnWithList;
import com.gaoyi.crm.db.query.MtcSyncedQuery;
import com.gaoyi.crm.repository.base.BaseRepository;
import com.gaoyi.crm.util.OKHttpUtil;
import com.gaoyi.crm.util.StringUtil;
import com.gaoyi.crm.util.ThreadManager;
import com.gaoyi.crm.util.Utils;

import java.util.Date;
import java.util.List;

public class PmnRepository extends BaseRepository<Pmn, PmnDao> {

    @Override
    protected int getIndex() {
        return 0;
    }

    @Override
    protected PmnDao getDao() {
        return mDatabase.getPmnDao();
    }

    public void insertPmn(Pmn pmn) {
        mDao.insert(pmn);
    }


    /**
     * 修改Pmn的 同步状态和时间
     */
    public void updatePmnSync(String id, Date syncedAt, int status) {
        ThreadManager.getInstance().execute(() -> mDao.updateStatusById(id, syncedAt.getTime(), status));
    }

    /**
     * 修改Pmn的 同步状态和时间
     */
    public void updatePmnSync(List<String> ids, Date syncedAt, int status, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            mDao.updateStatusByIds(ids, syncedAt.getTime(), status);
            OKHttpUtil.getInstance().post(() -> onResultListener.onSuccess(null));
        });
    }

    /**
     * 根据id查询Pmn
     */
    public Pmn getPmnById(String id) {
        return mDao.getPmnById(id);
    }

    public void updatePmn(Pmn bean) {
        mDao.update(bean);
    }

    /**
     * 获取Pmn本地表前limit条数据（Order By ModifyAt）
     *
     * @param limit 条数
     */
    public void getPmnByModifyAt(int limit, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            String custName = Utils.getCustomerName();
            List<PmnDto> list = mDao.getPmn(mDao.getLimitPmnSql(custName, limit));
            ApiResultData<Object> result = new ApiResultData<>();
            result.setStatus(ApiStatus.SUCCESS);
            result.setMessage(DbMsg.QUERY_SUCCESS);
            PagedList<PmnDto> pagedList = new PagedList<>();
            pagedList.setPageIndex(1);
            pagedList.setTotalPages(1);
            pagedList.setList(list);
            pagedList.setTotalCount(list.size());
            result.setData(pagedList);
            OKHttpUtil.getInstance().post(() -> onResultListener.onSuccess(result));
        });
    }

    /**
     * 根据查询条件获取本地Pmn表数据 （Order By ModifyAt），並且查詢Synced的總數
     *
     * @param query             查询条件
     * @param querySyncedStatus 查询Synced总数
     */
    public void getPmnByModifyAt(MtcSyncedQuery query, Integer querySyncedStatus, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            String custName = Utils.getCustomerName();
            List<PmnDto> customer = mDao.getPmn(mDao.getPmnSqlByModifyAt(custName, query, Utils.getOffset(query.getPageIndex()), Utils.getLimit()));
            int syncedTotal = mDao.getPmnCount(mDao.getPmnCountByModifyAtSql(custName, querySyncedStatus, query.getKeyWord(), query.getStartDate(), query.getEndDate()));
            int count = mDao.getPmnCount(mDao.getPmnCountByModifyAtSql(custName, query.getSyncedStatus(), query.getKeyWord(), query.getStartDate(), query.getEndDate()));
            getPmn(customer, query, syncedTotal, count, onResultListener);
        });
    }

    /**
     * 根据查询条件获取没有同步上传的Pmn表数据 （Order By ModifyAt）
     *
     * @param query 查询条件
     */
    public void getNoSyncPmn(MtcSyncedQuery query, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            String custName = Utils.getCustomerName();
            List<PmnWithList> customer = mDao.getNoSyncPmn(mDao.getNoSyncPmnSql(custName, query, Utils.getOffset(query.getPageIndex()), Utils.getLimit()));
            ApiResultData<Object> result = new ApiResultData<>();
            result.setStatus(ApiStatus.SUCCESS);
            result.setMessage(DbMsg.QUERY_SUCCESS);
            PagedList<PmnWithList> pagedList = new PagedList<>();
            int count = mDao.getPmnCount(mDao.getPmnCountByModifyAtSql(custName, query.getSyncedStatus(), query.getKeyWord(), query.getStartDate(), query.getEndDate()));
            int totalPages = (count / 10) + 1;
            pagedList.setPageIndex(query.getPageIndex());
            pagedList.setTotalPages(totalPages);
            pagedList.setList(customer);
            pagedList.setTotalCount(count);
            result.setData(pagedList);
            OKHttpUtil.getInstance().post(() -> onResultListener.onSuccess(result));
        });
    }


    /**
     * 根据查询条件获取本地Pmn表数据 （Order By SyncedAt）
     *
     * @param query 查询条件
     */
    public void getPmnBySyncedAt(MtcSyncedQuery query, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            String custName = Utils.getCustomerName();
            List<PmnDto> customer = mDao.getPmn(mDao.getPmnSqlBySyncedAt(custName, query, Utils.getOffset(query.getPageIndex()), Utils.getLimit()));
            int count = mDao.getPmnCount(mDao.getPmnCountBySyncedAtSql(custName, query.getSyncedStatus(), query.getKeyWord(), query.getStartDate(), query.getEndDate()));
            getPmn(customer, query, 0, count, onResultListener);
        });
    }

    private void getPmn(List<PmnDto> customer, MtcSyncedQuery query, int syncedTotal, int totalCount, OnResultListener onResultListener) {
        ApiResultData<Object> result = new ApiResultData<>();
        result.setStatus(ApiStatus.SUCCESS);
        result.setMessage(DbMsg.QUERY_SUCCESS);
        PagedList<PmnDto> pagedList = new PagedList<>();
//        int count = mDao.getPmnCountBySyncedAt(query.getSyncedStatus(), query.getKeyWord(), query.getStartDate(), query.getEndDate());
//        int totalPages = (count / 10) + 1;
        int totalPages = (totalCount / 10) + 1;
        pagedList.setPageIndex(query.getPageIndex());
        pagedList.setTotalPages(totalPages);
        pagedList.setList(customer);
        pagedList.setTotalCount(totalCount);
//        pagedList.setTotalCount(count);
        pagedList.setSyncTotalCount(syncedTotal);
        result.setData(pagedList);
        OKHttpUtil.getInstance().post(() -> onResultListener.onSuccess(result));
    }

    /**
     * 根据ids删除Pmn表数据
     *
     * @param list id列表
     */
    public void deletePmn(List<String> list, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            mDao.deleteByIds(list);
            ApiResultData<Object> result = new ApiResultData<>();
            result.setStatus(2000);
            result.setMessage(DbMsg.DELETE_SUCCESS);
            result.setData(null);
            OKHttpUtil.getInstance().post(() -> onResultListener.onSuccess(result));
        });
    }

    /**
     * 根据id删除Pmn表数据
     */
    public void deletePmn(String id, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            mDao.deleteById(id);
            if (onResultListener != null) {
                ApiResultData<Object> result = new ApiResultData<>();
                result.setStatus(2000);
                result.setMessage(DbMsg.DELETE_SUCCESS);
                result.setData(null);
                OKHttpUtil.getInstance().post(() -> onResultListener.onSuccess(result));
            }
        });
    }

    /**
     * 根据code查询Pmn
     */
    public void getPmnByCodeIsExist(String code, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            String pmn = mDao.getPmnByCode(code);
            ApiResultData<Boolean> result = new ApiResultData<>();
            result.setStatus(ApiStatus.SUCCESS);
            result.setMessage(DbMsg.QUERY_SUCCESS);
            result.setData(!TextUtils.isEmpty(pmn));
            OKHttpUtil.getInstance().post(() -> onResultListener.onSuccess(result));
        });
    }

    /**
     * 根据id查询Pmn，包括PmnAttach、PmnItemNo
     */
    public void getPmnWithListById(String id, OnResultListener onResultListener) {
        ThreadManager.getInstance().execute(() -> {
            PmnWithAttach pmnWithList = mDao.getPmnAllById(id);
            ApiResultData<PmnWithAttach> result = new ApiResultData<>();
            boolean isNull = pmnWithList == null;
            result.setStatus(isNull ? ApiStatus.FAIL : ApiStatus.SUCCESS);
            result.setMessage(isNull ? StringUtil.getString(R.string.no_data) : DbMsg.QUERY_SUCCESS);
            result.setData(pmnWithList);
            OKHttpUtil.getInstance().post(() -> onResultListener.onSuccess(result));
        });
    }
}
